﻿using System.Net;
using System.Text;

namespace Utils
{
    public class HttpHelper
    {
        public static string? HttpPost(string url, object data, KeyValuePair<string, string>[]? Header = null, string Method = "POST", Action<HttpStatusCode>? FailCallback = null)
        {
            try
            {
                string JsonString = JsonHelper.ObjectToJson(data);
                byte[] postBytes = Encoding.GetEncoding("utf-8").GetBytes(JsonString);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);

                Header?.ToList().ForEach(header =>
                {
                    myRequest.Headers.Add(header.Key, header.Value);
                });

                myRequest.Method = Method;
                myRequest.ContentType = "application/json";
                myRequest.ContentLength = postBytes.Length;
                myRequest.Proxy = null;
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(postBytes, 0, postBytes.Length);
                newStream.Close();
                // Get response
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

                if (myResponse.StatusCode != HttpStatusCode.OK && FailCallback != null) FailCallback(myResponse.StatusCode);

                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    string content = reader.ReadToEnd();
                    return content;
                }
            }
            catch
            {
                FailCallback?.Invoke(HttpStatusCode.InternalServerError);
                return null;
                //throw new Exception(ex.Message);
                //return ex.Message;
            }
        }

        public static string? HttpGet(string Url, KeyValuePair<string, string>[]? Header = null, Action<HttpStatusCode>? FailCallback = null)
        {
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            string Content = string.Empty;
            try
            {
                // 设置参数
                request = WebRequest.Create(Url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "GET"; //请求方式GET或POST
                //request.ContentType = "application/x-www-form-urlencoded";
                //request.Headers.Add("Authorization", "Basic YWRtaW46YWRtaW4=");
                Header?.ToList().ForEach(header =>
                {
                    request.Headers.Add(header.Key, header.Value);
                });

                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                if (response.StatusCode != HttpStatusCode.OK && FailCallback != null) FailCallback(response.StatusCode);

                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, Encoding.UTF8);
                //sr = new StreamReader(instream);
                //返回结果网页（html）代码
                Content = sr.ReadToEnd();
                return Content;
            }
            catch
            {
                FailCallback?.Invoke(HttpStatusCode.InternalServerError);
                return null;
            }
        }

        public static KeyValuePair<string, string>[]? GetHeader()
        {
            string? Token = CacheHelper.ReadFromSystemCache("Token")?.ToString();
            if (!string.IsNullOrEmpty(Token))
            {
                KeyValuePair<string, string> result = new KeyValuePair<string, string>("Authorization", $"Bearer {Token}");
                return new KeyValuePair<string, string>[] { result };
            }
            else return null;
        }

        public static string BuildGetParams(object obj)
        {
            string result = string.Empty;
            var PropertyList = obj.GetType().GetProperties().ToList();
            PropertyList.ForEach(item =>
            {
                result += item.Name + $"={item.GetValue(obj)?.ToString()}&";
            });

            if (!string.IsNullOrEmpty(result)) result = result.Substring(0, result.Length - 1);
            return result;
        }
    }
}